package com.whpost.service.service.t;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TFilesMapper;
import com.whpost.service.dao.t.TMenuDao;
import com.whpost.service.dao.t.TPermissionDao;
import com.whpost.service.dao.t.TRoleDao;
import com.whpost.service.entity.t.*;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.entity.tools.ServRtn;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: Yin Zhuoyi
 * @Date: 2021/12/15 11:16
 */
@Service
public class TRoleServices extends BaseServices<TFilesMapper, TFiles> {

    @Resource
    private TMenuDao tMenuDao;
    @Resource
    private TRoleDao tRoleDao;
    @Resource
    private TPermissionDao tPermissionDao;
    @Resource
    private TApiNonceService tApiNonceService;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",cxmc="";
            QueryWrapper<TRole> queryWrapper = new QueryWrapper<>();
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }

            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<TRole> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            //查询数据
            ListInfo<TRole> tRoleListInfo = new ListInfo<>();
            if (!StringUtils.isEmpty(cxmc))
            {
                queryWrapper.like("name",cxmc);
            }
            if (!"1".equals(loginId)) queryWrapper.eq("t_czy_id",loginId);
            else queryWrapper.eq("1","1");

            queryWrapper.orderByDesc("id");
            IPage<TRole> xmXmxxIPage = tRoleDao.selectPage(page,queryWrapper);

            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(xmXmxxIPage.getTotal());
            pageInfo.setCurPage(xmXmxxIPage.getCurrent());
            pageInfo.setPageSize(xmXmxxIPage.getSize());
            pageInfo.setPageTotal(xmXmxxIPage.getPages());

            tRoleListInfo.setPageInfo(pageInfo);
            tRoleListInfo.setListInfo(xmXmxxIPage.getRecords());
            tRoleListInfo.setUserId(loginId);

            //查询条件的值
            Map<String,Object> cxtjMap = new HashMap<>();
            cxtjMap.put("cxmc",cxmc);

            //返回前端的内容
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("cxjg",tRoleListInfo);
            rtnMap.put("cxtj",cxtjMap);

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo tree(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String per="";
            if (jsonObject.containsKey("per")) {
                per = jsonObject.getString("per");
            }
            Map<String,Object> rtnMap = new HashMap<>();
            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRole tRole = new TRole();
            String roleId = "";
            if ("1".equals(loginId)){

            }else{
                if (null==tCzy.getRoleId()){
                    return new ResultInfo(500,"该操作员没有角色信息！",null);
                }
                roleId = String.valueOf(tCzy.getRoleId());
                if (!StringUtils.isEmpty(roleId)) {
                    tRole = tRoleDao.selectById(roleId);
                }
                if (null==tRole){
                    return new ResultInfo(500,"角色信息不存在！",null);
                }
            }


            //需要打钩的元素，需要合并前台传过来的字符串
            List<String> perList=new ArrayList<>();
            if (!StringUtils.isEmpty(per)) perList = Arrays.asList(per.split(","));
            //ToolBean.info("per:"+per);
            //info("perList:"+perList.size());

            //角色所拥有的菜单和权限，不得超过此范围
            List<String> menuIds=new ArrayList<>();
            List<String> permissionId=new ArrayList<>();
            String menus = "";
            String permissions= "";
            if (!"1".equals(loginId)){
                menus = tRole.getMenuId();
                permissions= tRole.getPermissionId();
            }


            if (!StringUtils.isEmpty(menus)) menuIds = Arrays.asList(menus.split(","));
            if (!StringUtils.isEmpty(permissions)) permissionId = Arrays.asList(permissions.split(","));

            List<TMenu> ll_1 = new ArrayList<>(); //可以分配的菜单列表
            List<TPermission> ll_2 = new ArrayList<>();;   //可以分配的权限列表
            if ("1".equals(loginId)){
                ll_1 = tMenuDao.selectList(new QueryWrapper<TMenu>().eq("state","1"));
                ll_2 = tPermissionDao.selectList(new QueryWrapper<TPermission>().eq("state","1"));
            }else{
                ll_1 = tMenuDao.selectList(new QueryWrapper<TMenu>().eq("state","1").in("id",menuIds));
                ll_2 = tPermissionDao.selectList(new QueryWrapper<TPermission>().eq("state","1").in("id",permissionId));
            }


            String id="",pid="",name="",tid="";
            String treejson = "";
            treejson = "{id:\"pid\",pid:\"\",name: \"菜单权限列表\",chkDisabled:true},";
            for(int i = 0; i < ll_1.size(); i++)      //循环菜单 如果pid没有，则挂上主菜单的
            {
                TMenu tMenu = new TMenu();
                tMenu = ll_1.get(i);
                id="";pid="";tid="";
                id = "s_"+String.valueOf(tMenu.getId())+"";

                if (tMenu.getPid()==null)
                {
                    pid = "pid";
                } else {
                    pid = "s_"+String.valueOf(tMenu.getPid())+"";
                }

                if (perList.contains(id)) {
                    treejson += "{id:\""+id+"\",pId:\""+pid+"\", name: \""+tMenu.getName()+"[菜单]\",checked:true},";
                } else {
                    treejson += "{id:\""+id+"\",pId:\""+pid+"\", name: \""+tMenu.getName()+"[菜单]\"},";
                }

            }
            for(int i = 0; i < ll_2.size(); i++)
            {
                TPermission tPermission = new TPermission();
                tPermission = ll_2.get(i);
                id="";pid="";tid="";
                id = "p_"+tPermission.getId()+"";
                pid = "s_"+tPermission.getMenuId()+"";

                if (perList.contains(id)) {
                    treejson += "{id:\""+id+"\",pId:\""+pid+"\", name: \""+tPermission.getName()+"[权限]\",checked:true},";
                } else {
                    treejson += "{id:\""+id+"\",pId:\""+pid+"\", name: \""+tPermission.getName()+"[权限]\"},";
                }
            }
            String defaultId = "pid";
            rtnMap.put("defaultId", defaultId);
            rtnMap.put("treejson", JSON.parse("["+treejson+"]"));

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            Map<String,Object> infoMap = new HashMap<>();
            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            String lx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }

            if ("1".equals(lx) && StringUtils.isEmpty(id)){
                return new ResultInfo(500,"需要修改的信息丢失！",null);
            }

            //表单数据
            if ("1".equals(lx)){
                TRole tRole = new TRole();
                tRole = tRoleDao.selectById(id);
                infoMap.put("tRole",tRole);

                //找出权限
                String menuIds="",per="",permissionId="",perName="";
                if (tRole!=null)
                {
                    menuIds = tRole.getMenuId();
                    permissionId = tRole.getPermissionId();
                }
                if (!StringUtils.isEmpty(menuIds)) {
                    String s[] = menuIds.split(",");
                    for (int k = 0; k < s.length; k++) {
                        per += "s_" + s[k] + ",";
                        perName+=tMenuDao.getNameById(Long.parseLong(s[k]))+"[菜单],";
                    }
                }
                if (!StringUtils.isEmpty(permissionId)){
                    String p[] = permissionId.split(",");
                    for (int k=0;k<p.length;k++)
                    {
                        per +="p_"+p[k]+",";
                        perName+=tPermissionDao.selectById(Long.parseLong(p[k])).getName()+"[权限],";
                    }
                }

                if (!StringUtils.isEmpty(per)) per = per.substring(0, per.length() - 1);
                if (!StringUtils.isEmpty(perName)) perName = perName.substring(0, perName.length() - 1);

                infoMap.put("per",per);
                infoMap.put("perName",perName);
            }

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",infoMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo save(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",nonce_ms="",nonce_zhi="",jsmc="",per="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("jsmc")) {
                jsmc = jsonObject.getString("jsmc");
            }
            if (jsonObject.containsKey("per")) {
                per = jsonObject.getString("per");
            }
            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }
            //参数校验
            if (StringUtils.isEmpty(lx) || StringUtils.isEmpty(jsmc) || StringUtils.isEmpty(per)){
                return new ResultInfo(500,"表单数据丢失！",null);
            }
            if ("1".equals(lx) && StringUtils.isEmpty(id)){
                return new ResultInfo(500,"需要修改的信息丢失！",null);
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"角色增改操作");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRole tRole = new TRole();
            ResultInfo resultInfo = new ResultInfo();
            if ("1".equals(lx)){
                tRole = tRoleDao.selectById(id);
            }

            //校验提交的权限，是否在限制范围内
            List<String> v_submenu = new Vector<String>();
            List<String> v_permission = new Vector<String>();
            String ss="",ps="";
            //前台获取的参数，处理后，形成菜单和权限两个数字
            String a[] = per.split(",");
            //如果是1 ，不做校验
            //角色所拥有的菜单和权限，不得超过此范围
            List<String> menuIds=new ArrayList<>();
            List<String> permissionId=new ArrayList<>();
            if (!"1".equals(loginId)){
                TRole userTRole = new TRole();
                String roleId = String.valueOf(tCzy.getRoleId());
                if (!StringUtils.isEmpty(roleId)) {
                    userTRole = tRoleDao.selectById(roleId);
                }
                if (null==userTRole){
                    return new ResultInfo(500,"该操作员没有角色信息！",null);
                }
                String menus = "";
                String permissions= "";
                menus = userTRole.getMenuId();
                permissions= userTRole.getPermissionId();
                if (!StringUtils.isEmpty(menus)) menuIds = Arrays.asList(menus.split(","));
                if (!StringUtils.isEmpty(permissions)) permissionId = Arrays.asList(permissions.split(","));
                ToolBean.info("menus:"+menus);
                ToolBean.info("menuIds:"+menuIds.size());
            }
            for (int i=0;i<a.length;i++)
            {
                if (a[i].indexOf("s_")>=0)
                {
                    String str="";
                    str = a[i].replaceAll("s_","");
                    if (!"1".equals(loginId) && !menuIds.contains(str)) //如果不是admin并且不包含，则提示
                    {
                        return new ResultInfo(500,"添加了权限之外的菜单信息！"+str,null);
                    }
                    v_submenu.add(str);
                }
                else if (a[i].indexOf("p_")>=0)
                {
                    String str="";
                    str = a[i].replaceAll("p_","");
                    if (!"1".equals(loginId) && !permissionId.contains(str)) //如果不是admin并且不包含，则提示
                    {
                        return new ResultInfo(500,"添加了权限之外的权限信息！",null);
                    }
                    v_permission.add(str);
                }
            }
            for (int k=0;k<v_submenu.size();k++)
            {
                ss+=v_submenu.get(k)+",";
            }
            for (int k=0;k<v_permission.size();k++)
            {
                ps+=v_permission.get(k)+",";
            }
            if (!"".equals(ss)) {
                ss = ss.substring(0,ss.length()-1);
            }
            if (!"".equals(ps)) {
                ps = ps.substring(0,ps.length()-1);
            }
            tRole.setName(jsmc);
            tRole.setZjm(ToolBean.getPy(jsmc));
            tRole.setMenuId(ss);
            tRole.setPermissionId(ps);

            //存盘逻辑 1 修改  0 新增
            if ("1".equals(lx)){
                tRoleDao.updateById(tRole);
                resultInfo = new ResultInfo(2, "修改成功！",null);
            }else{
                tRole.setTCzyId(tCzy.getId());
                tRoleDao.insert(tRole);
                resultInfo = new ResultInfo(1, "新增成功！",null);
            }
            return backRtn(resultInfo,loginId);
        }
    }
    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String ids = "";
            if (jsonObject.containsKey("ids")) {
                ids = jsonObject.getString("ids");
            }
            String [] code = ids.split(",");
            int i=0;
            String str="";

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            TRole tRole = new TRole();

            for(i=0;i<code.length;i++)
            {
                if (code[i].equals("")) {
                    continue;
                }
                Long id = Long.parseLong(code[i].replaceAll("\\D","").trim());
                tRole = new TRole();
                tRole = tRoleDao.selectById(id);

                //暂时只能删除自己维护的角色！
                if (!"1".equals(loginId)){
                    if (null==tRole.getTCzyId()){
                        str+="'"+tRole.getName()+"'没有权限删除！，";
                        continue;
                    }
                    if (!tRole.getTCzyId().equals(tCzy.getId())){
                        str+="'"+tRole.getName()+"'无法删除非自己维护的角色！，";
                        continue;
                    }
                }
                //看下有没有用户拥有这个角色
                if (gettCzyDao().selectCount(new QueryWrapper<TCzy>().eq("role_id",id))>0){
                    str+="'"+tRole.getName()+"'有对应的用户信息，无法删除！，";
                    continue;
                }
                tRoleDao.deleteById(id);
            }
            ResultInfo resultInfo;
            if (str.length()>0) {
                str = str.substring(0,str.length()-1);
            }
            if (!StringUtils.isEmpty(str))
            {
                str="["+str+"]，无法删除！";
                resultInfo = new ResultInfo(500, str,null);
            }
            else {
                resultInfo = new ResultInfo(0, str,null);
            }
            return backRtn(resultInfo,loginId);
        }
    }
}
